import { useState } from 'react';
import { connect } from 'react-redux';
import register from '../../store/action/register';
import { withRouter } from 'react-router-dom';
import { useBack } from "../../common/hook/index";

function Register (props) {
  const { setDeg } = props;
  const [user, setUser] = useState("miaov00");
  const [password, setPassword] = useState("miaov12");
  const [repassword, setRepassword] = useState("miaov12");
  const [vcode, setVcode] = useState("");
  const [showVcode, setShowVcode] = useState(false);
  const [vscodeSrc, setVscodeSrc] = useState('/zy/user/verify?' + new Date().getTime());
  const back = useBack(props.history);
  function toRegister () {
    props.dispatch(register({
      verify: vcode,
      username: user,
      password: password,
      repassword: password,
    })).then((res) => {
      alert(res.msg);
      setTimeout(() => {
        if (res.code === 0) {
          //back();
          setDeg(0);
        }
        setVscodeSrc('/zy/user/verify?' + Date.now());
      }, 100);
    })
  }
  return (
    <div className="register_box">
      <h3>注册账号</h3>
      <div className="register_form">
        <p>
          <input
            type="text"
            name="username"
            value={user}
            onChange={(e) => {
              setUser(e.target.value);
            }}
            placeholder="用户名" />
        </p>
        <p>
          <input
            type="password"
            name="userpassword"
            value={password}
            onChange={(e) => {
              setPassword(e.target.value);
            }}
            placeholder="请输入密码" />
        </p>
        <p>
          <input
            type="password"
            name="userpassword2"
            value={repassword}
            onChange={(e) => {
              setRepassword(e.target.value);
            }}
            placeholder="请输入密码" />
        </p>
        <p className="mima clearfix">
          <input
            type="text"
            name="vcode"
            value={vcode}
            autoComplete="off"
            onChange={(e) => {
              setVcode(e.target.value);
            }}
            onFocus={() => {
              setShowVcode(true);
            }}
            placeholder="请输入验证码" />
          {
            showVcode ? <img src={vscodeSrc} onClick={() => {
              setVscodeSrc('/zy/user/verify?' + new Date().getTime())
            }} /> : null
          }
        </p>
        <button className="form_btn" onClick={() => { toRegister() }}>马上注册</button>
        <p className="form_tip">已有帐号？<a onClick={() => { setDeg(0) }}>立即登录</a></p>
      </div>
    </div>
  )
}

export default connect((res) => {
  return res;
})(withRouter(Register));